<template>
  <div class="order_list">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="clearfix_text">操作</span>
        <span>
          <el-button style="float: right;" type="primary" @click="getList()">搜索</el-button>
          <el-button style="float: right;margin-right: 10px;" type="primary" @click="clearSearch">重置</el-button>
          <el-button style="float: right;" type="primary">导出</el-button>
        </span>
      </div>
      <el-form :inline="true" :model="orderForm" class="demo-form-inline">
        <el-form-item label="订单号">
          <el-input v-model="orderForm.orderNo" placeholder="订单号" />
        </el-form-item>
        <el-form-item label="装货单位">
          <el-input v-model="loadCompany" placeholder="装货单位" @change="changeCompany('loadCompany')" />
        </el-form-item>
        <el-form-item label="卸货单位">
          <el-input v-model="unloadCompany" placeholder="卸货单位" @change="changeCompany('unloadCompany')" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="sendTimeDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="creationTimeRange"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="orderForm.orderStatus" multiple filterable placeholder="状态">
            <el-option
              v-for="item in orderStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card table_card">
      <div slot="header" class="clearfix">
        <span class="clearfixText">
          <el-button
            v-for="(item, index) in tableBtnList"
            :key="index"
            type="text"
            :class="tableBtnIndex === index ? 'pitchUpStatus' : ''"
            @click="tableFiltrate(index)"
          >{{ item }}</el-button>
        </span>
        <el-button type="primary" class="right_btn">自定义列表</el-button>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column label="订单号" width="120">
          <template slot-scope="scope">
            <el-link :underline="false" @click="pushDetail(scope.row.orderNo)">{{ scope.row.orderNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="货物名称" width="120" />
        <el-table-column prop="loadCompany" label="装货单位" />
        <el-table-column label="装货地">
          <template slot-scope="{row}">
            {{ row.loadProvince }}-{{ row.loadCity }}-{{ row.loadDistrict }}-{{
              row.loadAddress
            }}
          </template>
        </el-table-column>
        <el-table-column prop="unloadCompany" label="卸货单位" />
        <el-table-column prop="address" label="卸货地">
          <template slot-scope="{row}">
            {{ row.unloadProvince }}-{{ row.unloadCity }}-{{ row.unloadDistrict }}-{{
              row.loadAddress
            }}
          </template>
        </el-table-column>
        <el-table-column prop="totalWeight" label="订单重量（吨）" />
        <el-table-column prop="validWeight" label="待派单重量（吨）" />
        <el-table-column prop="countWeight" label="已装重量（吨）" />
        <el-table-column prop="createdTime" label="创建时间" />
        <el-table-column label="状态">
          <template slot-scope="{row}">{{ orderStatus(row.status) }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <span v-if="row.status === 'PENDING'">
              <el-button type="text" @click="toDelivery(row.orderNo,row.totalWeight)">派单</el-button>
            </span>
            <span v-if="row.status === 'PROCESSING'">
              <el-button type="text" @click="$router.push({ name: 'anewdeliveryList', query: { id: row.orderNo,weight:row.totalWeight }})">重新派单</el-button>
            </span>
            <span v-if="row.status === 'PENDING'">
              <el-button type="text" @click="$router.push({ name: 'revampOrder', query: { row }})">修改</el-button>
            </span>
            <span v-if="row.status === 'PENDING'">
              <el-button type="text" @click="dialogShow('取消',row.orderNo)">取消</el-button>
            </span>
            <span v-if="row.status === 'PENDING' || row.status === 'PROCESSING'">
              <el-button type="text" @click="dialogShow('终止',row.orderNo)">终止</el-button>
            </span>
            <span v-if="row.status === 'PROCESSING'">
              <el-button type="text" @click="dialogShow('选择司机',row.orderNo)">代司机接单</el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="pagination">
      <el-pagination
        :current-page="pager.current"
        :page-sizes="pager.sizes"
        :page-size="pager.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.total"
        @size-change="changeTableSize"
        @current-change="changeTableCurrent"
      />
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      center
    >
      <span v-if="dialogTitle === '取消'">是否确认取消该订单？</span>
      <span v-if="dialogTitle === '终止'" style="font-size:16px;">
        <div style="text-align: center;">是否确认终止该订单？</div>
        <div style="text-align: center;margin-top:15px;">终止之后该订单不可进行派单接单操作</div>
      </span>
      <el-table
        v-if="dialogTitle === '选择司机'"
        ref="multipleTable"
        :data="dialogTableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          label="司机姓名"
          prop="name"
        />
        <el-table-column
          prop="mobile"
          label="手机号"
        />
        <el-table-column
          prop="licenseNo"
          label="车牌号"
        />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="centerDialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, postCancelOrder, postFinishOrder, getWayillDriver, postProxyAccept } from '@/api/tms/order'
export default {
  name: 'OrderList',
  components: {
  },
  data() {
    return {
      listLoading: false,
      loadCompany: '',
      unloadCompany: '',
      sendTimeDateRange: [],
      dialogVisible: false,
      dialogTitle: '',
      dialogId: '',
      // 分页
      pager: {
        total: 0,
        sizes: [20, 50, 100],
        size: 20,
        current: 1
      },
      // 创建时间
      creationTime: [],
      orderForm: {
        orderNo: '',
        startDate: '',
        endDate: '',
        loadCompany: [],
        unloadCompany: [],
        orderStatus: []
      },
      tableBtnIndex: 0,
      // 订单状态选择列表
      orderStatusList: [{
        value: 'PENDING',
        label: '待派单'
      }, {
        value: 'PROCESSING',
        label: '已派单'
      }, {
        value: 'STOP',
        label: '已终止'
      }, {
        value: 'DONE',
        label: '已完成'
      }, {
        value: 'CANCEL',
        label: '已取消'
      }],
      // 表单筛选按钮列表
      tableBtnList: ['全部', '未完成', '已完成', '已取消'],
      tableData: [],
      dialogTableData: [],
      driverReceivingList: []
    }
  },
  computed: {
    orderStatus: () => {
      return (val) => {
        if (val === 'PENDING') {
          return '待派单'
        } else if (val === 'PROCESSING') {
          return '已派单'
        } else if (val === 'STOP') {
          return '已终止'
        } else if (val === 'DONE') {
          return '已完成'
        } else if (val === 'CANCEL') {
          return '已取消'
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      const data = {
        ...this.orderForm,
        size: this.pager.size,
        current: this.pager.current
      }
      const { records, total } = await getOrderList(data)
      this.tableData = records
      this.pager.total = total
      this.listLoading = false
    },
    // 派单
    toDelivery(oid, weight) {
      this.$router.push({ path: '/orderManage/deliveryList', query: { id: oid, weight }})
    },
    // 重置
    clearSearch() {
      this.orderForm = {
        orderNo: '',
        startDate: '',
        endDate: '',
        loadCompany: [],
        unloadCompany: [],
        orderStatus: []
      }
      this.sendTimeDateRange = []
      this.loadCompany = ''
      this.unloadCompany = ''
      this.getList()
    },
    // 创建时间赋值
    creationTimeRange() {
      if (this.sendTimeDateRange) {
        this.orderForm.startDate = this.sendTimeDateRange[0] + ' 00:00:00'
        this.orderForm.endDate = this.sendTimeDateRange[1] + ' 23:59:59'
      } else {
        this.orderForm.startDate = ''
        this.orderForm.endDate = ''
      }
    },
    changeCompany(key) {
      this.orderForm[key] = [this[key]]
    },
    tableFiltrate(index) {
      this.tableBtnIndex = index
      if (index === 0) {
        this.orderForm.orderStatus = []
      } else if (index === 1) {
        this.orderForm.orderStatus = ['PENDING', 'PROCESSING', 'STOP']
      } else if (index === 2) {
        this.orderForm.orderStatus = ['DONE']
      } else if (index === 3) {
        this.orderForm.orderStatus = ['CANCEL']
      }
      this.getList()
    },
    changeTableCurrent(val) {
      this.pager.current = val
      this.getList()
    },
    changeTableSize(val) {
      this.pager.size = val
      this.pager.current = 1
      this.getList()
    },
    async dialogShow(title, id) {
      this.dialogTitle = title
      this.dialogId = id
      if (title === '选择司机') {
        try {
          const res = await getWayillDriver(id)
          this.dialogTableData = res
        } catch {
          this.$message.error('服务器错误')
        }
      }
      this.dialogVisible = true
    },
    async centerDialogConfirm() {
      if (this.dialogTitle === '取消') {
        try {
          await postCancelOrder(this.dialogId)
          this.$message.success('操作成功')
          this.getList()
        } catch {
          return
        }
      } else if (this.dialogTitle === '终止') {
        try {
          await postFinishOrder(this.dialogId)
          this.$message.success('操作成功')
          this.getList()
        } catch {
          return
        }
      } else if (this.dialogTitle === '选择司机') {
        try {
          await postProxyAccept({ orderNo: this.dialogId, drivers: this.dialogTableData })
          this.$message.success('操作成功')
        } catch {
          console.log()
        }
      }
      this.dialogVisible = false
    },
    // 表格选择
    handleSelectionChange(e) {
      this.driverReceivingList = e
    },
    pushDetail(id) {
      this.$router.push({ name: 'orderDetail', query: { id }})
    }
  }
}
</script>
<style lang="scss">
.order_list {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both;
  }

  .table_card {
    .el-card__header {
      border: 0;
    }
    .clearfix {
      .clearfixText {
        button {
          color: #45454b;
          font-weight: 700;
          margin: 0;
          padding: 0 15px;
          border-radius: 0;
        }
        .pitchUpStatus {
          color: #1890ff;
        }
        button:nth-child(n + 2) {
          border-left: 2px solid #45454b;
        }
      }
    }
    .el-card__body {
      padding-top: 0;
    }
  }
  .el-form-item {
    margin-left: 30px;
  }
}
</style>
